package furns.filter;

import com.google.gson.Gson;
import furns.entity.Member;
import furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

//这是用于权限验证的过滤器, 对指定的url进行验证
//如果登录过, 就放行, 如果没有登录，就回到登录页面
public class AuthFilter implements Filter {
    //后面我们把要排除的url放入到excludedUrls
    private List<String> excludedUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取到配置excludedUrls
        String strExcludedUrls = filterConfig.getInitParameter("excludeUrls");
        //通过,分割,拿到url的数组
        String[] splitUrl = strExcludedUrls.split(",");
        //将 splitUrl 转成 List
        excludedUrls = Arrays.asList(splitUrl);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        //获取请求的url
        String servletPath = request.getServletPath();
        //判断是否要进行验证
        if (!excludedUrls.contains(servletPath)) {
            //获取session中的member对象
            HttpSession session = request.getSession();
            Member member = (Member)session.getAttribute("member");
            //判断是否登录
            //如果member不为null，还应当判断member是不是管理员，在根据获取到的url
            //进行对应的处理，如果该用户不是admin，但是他访问后台就跳转到首页即可
            if (member == null){ //没有登录
                //这里要判断以下是不是Ajax请求
                if(!WebUtils.isAjaxRequest(request)) {
                    //这里只能用请求转发,不能用重定向,因为转发到登录界面,转发不走过滤器
                    request.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                }else {
                    //如果是ajax请求
                    HashMap<String, Object> resultMap = new HashMap<>();
                    resultMap.put("url","views/member/login.jsp");
                    String regStr = new Gson().toJson(resultMap);
                    servletResponse.getWriter().write(regStr);
                }
                //返回
                return;
            }
        }
        //继续访问
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
